<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属公司" prop="orgguid">
        <el-select v-model="queryParams.orgguid" placeholder="请选择所属公司" clearable size="small">
          <el-option
            v-for="item in orgs"
            :key="item.guid"
            :label="item.name"
            :value="item.guid"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择部门类型" clearable size="small">
          <el-option
            v-for="dict in types"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="parseInt(dict.dictValue)"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['organization:department:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['organization:department:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['organization:department:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['organization:department:export']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="departmentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="编号" align="center" prop="code" />
      <el-table-column label="所属公司" align="center" prop="orgname" />
      <el-table-column label="部门类型" align="center" prop="typename" />
      <el-table-column label="部门金蝶编码" align="center" prop="kingdeenum" />
      <el-table-column label="备注" align="center" prop="remark" />
<!--      <el-table-column label="创建人" align="center" prop="operatorname" />-->
      <el-table-column label="创建时间" align="center" prop="createtime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createtime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="statusname" :formatter="statusFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['organization:department:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['organization:department:remove']"
          >删除</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleOn(scope.row, scope.row.status)"
            v-hasPermi="['organization:department:remove']"
          ><div v-if="scope.row.status == 1">禁用</div>
            <div v-else-if="scope.row.status == 0">启用</div></el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" :inline="true" label-width="180px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" clearable placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="所属公司" prop="orgguid" >
          <el-select v-model="form.orgguid" clearable placeholder="请选择公司" filterable clearable >
            <el-option
              v-for="item in orgs"
              :key="item.guid"
              :label="item.name"
              :value="item.guid"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门" prop="upDepcode" >
          <el-select v-model="upDepcode" placeholder="请选择部门" filterable clearable >
            <el-option
              v-for="item in departments"
              :key="item.guid"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="form.code" @blur="checkCode" clearable placeholder="请输入编号" />
        </el-form-item>
        <el-form-item label="部门类型" prop="type">
          <el-select v-model="form.type" clearable placeholder="请选择部门类型">
            <el-option
              v-for="dict in types"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="负责人" prop="operatorid">
          <el-input v-model="form.manager" clearable placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item label="负责人电话" prop="operatorid">
          <el-input type="number" v-model="form.managertel" clearable placeholder="请输入负责人电话" />
        </el-form-item>
        <el-form-item label="是否计划部门标识" prop="flag">
          <el-radio-group v-model="flag">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="金蝶编号" prop="kingdeenum">
          <el-input v-model="form.kingdeenum" clearable placeholder="请输入金蝶编号" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" style="width: 206px;" :rows="3" v-model="form.remark" clearable placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDepartment, getDepartment, delDepartment, addDepartment, updateDepartment, disableDepartment, exportDepartment,findOrg ,findAll} from "@/api/organization/department";
import { findOrganizationList } from "@/api/public";
import { getDicts } from "@/api/system/dict/data";
export default {
  name: "Department",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      departmentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        code: null,
        description: null,
        orgguid: null,
        manager: null,
        managertel: null,
        remark: null,
        operatorid: null,
        createtime: null,
        dingtalkdepid: null,
        type: null,
        status: null,
        flag: null,
        kingdeenum: null
      },
      // 表单参数
      form: {
        flag: "0",
      },
      flag: "0",
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        orgguid: [
          { required: true, message: "所属公司不能为空", trigger: "change" }
        ],
        code: [
          { required: true, message: "部门编码不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "部门类型不能为空", trigger: "change" }
        ],
      },
      orgs:[],
      departments: [],
      types: [],
      upDepcode: ''
    };
  },
  created() {
    this.getList();
    this.findOrganizationList();
    this.getTypes();
  },
  watch: {
    'flag': function(val) {
      this.form.flag = val;
    },
    'form.orgguid': function(val) {
      if (!val) return;
      this.findAll(val);
    }
  },
  methods: {
    statusFormat: function(row, column) {
      return row.status == 1 ? '正常' : '禁用';
    },
    checkCode: function() {
      if (this.form.code.length > 3) {
        this.msgInfo('部门编码必须是3位');
        this.form.code = '';
      }
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      listDepartment(this.queryParams).then(response => {
        this.departmentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        guid: null,
        name: null,
        // upDepcode: null,
        code: null,
        description: null,
        orgguid: null,
        manager: null,
        managertel: null,
        remark: null,
        operatorid: null,
        createtime: null,
        dingtalkdepid: null,
        type: null,
        status: 0,
        flag: null,
        kingdeenum: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.guid)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const guid = row.guid || this.ids
      getDepartment(guid).then(response => {
        const data = response.data;
        const len = data.code.length;
        this.upDepcode = data.code.substr(0, len - 3);
        data.code = data.code.substring(len - 3, len);
        this.form = data;
        this.open = true;
        this.title = "修改";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.upDepcode) {
            this.form.code = this.upDepcode + this.form.code;
          }
          if (this.form.guid != null) {
            updateDepartment(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDepartment(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /*获取公司*/
    findOrganizationList: function () {
      findOrganizationList().then(response => {
        this.orgs = response.data;
      });
    },
    /*获取部门*/
    findAll: function (orgid) {
      findAll(orgid).then(response => {
        this.departments = response.data;
      });
    },
    /*获取部门*/
    getTypes: function () {
      getDicts('department_type').then(response => {
        this.types = response.data;
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const guids = row.guid || this.ids;
      this.$confirm('是否确认删除该数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delDepartment(guids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 启用禁用按钮 */
    handleOn(row, status) {
      const guids = row.guid || this.ids;
      let strTitle = "启用";
      if (1 == status){
        strTitle = "禁用";
      }
      this.$confirm('是否确认启用/禁用该数据项?', "警告", {
          confirmButtonText: strTitle,
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          console.log('guids:', guids)
          return disableDepartment(guids);
        }).then(() => {
          this.getList();
          this.msgSuccess("操作成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportDepartment(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
